/**
 * 地图控件管理模块
 * @description 管理地图上的各种控件，专注于初始化时配置图标
 */

import { ref, reactive } from 'vue';
import { TOOL_BUTTONS, DEFAULT_MAP_VIEWS } from '../constants.js';

/**
 * 地图控件管理器类
 * @class MapControls
 */
export class MapControls {
  constructor(mapEngine, options = {}) {
    this.mapEngine = mapEngine;
    this.options = options;
    this.controls = new Map();
    this.toolButtons = reactive(new Map());
    this.isFullscreen = ref(false);
    
    // 控件状态
    this.controlState = reactive({
      compassEnabled: true,
      scaleEnabled: true,
      mousePositionEnabled: false,
      overviewMapEnabled: false,
      zoomControlEnabled: true
    });

    // 事件回调
    this.callbacks = {
      onButtonClick: null,
      onFullscreenChange: null,
      onControlToggle: null
    };
    
    this.init();
  }

  /**
   * 初始化控件管理器
   * @private
   */
  init() {
    const map = this.mapEngine?.getInstance();
    if (!map) return;

    // 根据配置添加默认控件
    this._setupDefaultControls();
    
    // 绑定全屏事件
    this._bindFullscreenEvents();
  }

  /**
   * 设置默认控件
   * @private
   */
  _setupDefaultControls() {
    const { 
      showActions = true,
      lineControl = false,
      questionControl = false 
    } = this.options;

    if (showActions) {
      this.addToolButton('position', {
        ...TOOL_BUTTONS.position,
        onClick: () => this._handlePositionReset()
      });

      this.addToolButton('fullscreen', {
        ...TOOL_BUTTONS.fullscreen,
        onClick: () => this.toggleFullscreen()
      });
    }

    if (lineControl) {
      this.addToolButton('line', {
        ...TOOL_BUTTONS.line,
        onClick: () => this._triggerCallback('onButtonClick', 'lineButtonClick')
      });
    }

    if (questionControl) {
      this.addToolButton('question', {
        ...TOOL_BUTTONS.question,
        onClick: () => this._triggerCallback('onButtonClick', 'questionButtonClick')
      });
    }
  }

  /**
   * 添加工具按钮
   * @param {string} id - 按钮ID
   * @param {Object} config - 按钮配置
   * @param {string} config.title - 按钮标题
   * @param {string} config.className - CSS类名
   * @param {string} config.icon - 图标URL或类名
   * @param {Function} config.onClick - 点击回调
   * @param {string} config.position - 位置 ('top-left' | 'top-right' | 'bottom-left' | 'bottom-right')
   * @returns {Object} 按钮控件实例
   */
  addToolButton(id, config = {}) {
    const map = this.mapEngine?.getInstance();
    if (!map) return null;

    const {
      title = '',
      className = '',
      icon = '',
      onClick = null,
      position = 'top-right',
      tooltip = title
    } = config;

    try {
      // 创建按钮元素
      const buttonElement = this._createButtonElement(id, {
        title,
        className,
        icon,
        tooltip
      });

      // 创建控件
      const control = new mars3d.control.ToolButton({
        position,
        insertIndex: this.toolButtons.size,
        element: buttonElement
      });

      // 添加到地图
      map.addControl(control);

      // 绑定点击事件
      if (onClick) {
        buttonElement.addEventListener('click', (event) => {
          event.preventDefault();
          onClick(event);
        });
      }

      // 存储控件信息
      const buttonInfo = {
        id,
        control,
        element: buttonElement,
        config,
        active: false,
        visible: true
      };

      this.controls.set(id, buttonInfo);
      this.toolButtons.set(id, buttonInfo);

      return control;

    } catch (error) {
      console.error('Failed to add tool button:', error);
      return null;
    }
  }

  /**
   * 创建按钮元素
   * @private
   * @param {string} id - 按钮ID
   * @param {Object} config - 按钮配置
   * @returns {HTMLElement} 按钮元素
   */
  _createButtonElement(id, config) {
    const { title, className, icon, tooltip } = config;
    
    const button = document.createElement('div');
    button.className = `tool-button ${className}`;
    button.title = tooltip;
    button.id = `tool-button-${id}`;
    
    // 设置按钮样式
    Object.assign(button.style, {
      width: '32px',
      height: '32px',
      backgroundColor: 'rgba(48, 51, 54, 0.8)',
      border: '1px solid rgba(255, 255, 255, 0.2)',
      borderRadius: '4px',
      cursor: 'pointer',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      margin: '2px',
      transition: 'all 0.2s ease'
    });

    // 添加图标
    if (icon) {
      if (icon.startsWith('http') || icon.startsWith('/')) {
        // 图片图标
        const img = document.createElement('img');
        img.src = icon;
        img.style.width = '20px';
        img.style.height = '20px';
        button.appendChild(img);
      } else {
        // CSS类图标
        const iconElement = document.createElement('i');
        iconElement.className = icon;
        iconElement.style.color = '#ffffff';
        iconElement.style.fontSize = '16px';
        button.appendChild(iconElement);
      }
    } else {
      // 文字标题
      button.textContent = title;
      button.style.color = '#ffffff';
      button.style.fontSize = '12px';
    }

    // 添加hover效果
    button.addEventListener('mouseenter', () => {
      button.style.backgroundColor = 'rgba(255, 255, 255, 0.1)';
    });

    button.addEventListener('mouseleave', () => {
      const isActive = this.getButtonActiveState(id);
      button.style.backgroundColor = isActive 
        ? 'rgba(0, 122, 255, 0.8)' 
        : 'rgba(48, 51, 54, 0.8)';
    });

    return button;
  }

  /**
   * 移除工具按钮
   * @param {string} id - 按钮ID
   * @returns {boolean} 是否成功移除
   */
  removeToolButton(id) {
    const buttonInfo = this.controls.get(id);
    if (!buttonInfo) return false;

    const map = this.mapEngine?.getInstance();
    if (map && buttonInfo.control) {
      map.removeControl(buttonInfo.control);
    }

    this.controls.delete(id);
    this.toolButtons.delete(id);
    
    return true;
  }

  /**
   * 切换按钮激活状态
   * @param {string} id - 按钮ID
   * @param {boolean} active - 是否激活
   */
  toggleButtonActive(id, active = null) {
    const buttonInfo = this.controls.get(id);
    if (!buttonInfo) return;

    const newActiveState = active !== null ? active : !buttonInfo.active;
    buttonInfo.active = newActiveState;

    // 更新按钮样式
    if (buttonInfo.element) {
      buttonInfo.element.style.backgroundColor = newActiveState 
        ? 'rgba(0, 122, 255, 0.8)' 
        : 'rgba(48, 51, 54, 0.8)';
    }

    this._triggerCallback('onControlToggle', { id, active: newActiveState });
  }

  /**
   * 获取按钮激活状态
   * @param {string} id - 按钮ID
   * @returns {boolean} 是否激活
   */
  getButtonActiveState(id) {
    const buttonInfo = this.controls.get(id);
    return buttonInfo ? buttonInfo.active : false;
  }

  /**
   * 显示/隐藏按钮
   * @param {string} id - 按钮ID
   * @param {boolean} visible - 是否显示
   */
  toggleButtonVisibility(id, visible = null) {
    const buttonInfo = this.controls.get(id);
    if (!buttonInfo) return;

    const newVisibleState = visible !== null ? visible : !buttonInfo.visible;
    buttonInfo.visible = newVisibleState;

    if (buttonInfo.element) {
      buttonInfo.element.style.display = newVisibleState ? 'flex' : 'none';
    }
  }

  /**
   * 添加罗盘控件
   * @param {Object} options - 罗盘配置选项
   * @returns {Object} 罗盘控件实例
   */
  addCompass(options = {}) {
    const map = this.mapEngine?.getInstance();
    if (!map) return null;

    const compassConfig = {
      position: options.position || 'top-right',
      ...options
    };

    try {
      const compass = new mars3d.control.Compass(compassConfig);
      map.addControl(compass);
      
      this.controls.set('compass', {
        id: 'compass',
        control: compass,
        config: compassConfig
      });

      this.controlState.compassEnabled = true;
      return compass;

    } catch (error) {
      console.error('Failed to add compass:', error);
      return null;
    }
  }

  /**
   * 添加比例尺控件
   * @param {Object} options - 比例尺配置选项
   * @returns {Object} 比例尺控件实例
   */
  addScale(options = {}) {
    const map = this.mapEngine?.getInstance();
    if (!map) return null;

    const scaleConfig = {
      position: options.position || 'bottom-left',
      ...options
    };

    try {
      const scale = new mars3d.control.Scale(scaleConfig);
      map.addControl(scale);
      
      this.controls.set('scale', {
        id: 'scale',
        control: scale,
        config: scaleConfig
      });

      this.controlState.scaleEnabled = true;
      return scale;

    } catch (error) {
      console.error('Failed to add scale:', error);
      return null;
    }
  }

  /**
   * 添加鼠标位置显示控件
   * @param {Object} options - 鼠标位置配置选项
   * @returns {Object} 鼠标位置控件实例
   */
  addMousePosition(options = {}) {
    const map = this.mapEngine?.getInstance();
    if (!map) return null;

    const mousePositionConfig = {
      position: options.position || 'bottom-right',
      template: options.template || '经度:{lng} 纬度:{lat} 海拔:{alt}m',
      ...options
    };

    try {
      const mousePosition = new mars3d.control.MousePosition(mousePositionConfig);
      map.addControl(mousePosition);
      
      this.controls.set('mousePosition', {
        id: 'mousePosition',
        control: mousePosition,
        config: mousePositionConfig
      });

      this.controlState.mousePositionEnabled = true;
      return mousePosition;

    } catch (error) {
      console.error('Failed to add mouse position:', error);
      return null;
    }
  }

  /**
   * 添加缩放控件
   * @param {Object} options - 缩放控件配置选项
   * @returns {Object} 缩放控件实例
   */
  addZoomControl(options = {}) {
    const map = this.mapEngine?.getInstance();
    if (!map) return null;

    const zoomConfig = {
      position: options.position || 'top-left',
      ...options
    };

    try {
      const zoomControl = new mars3d.control.Zoom(zoomConfig);
      map.addControl(zoomControl);
      
      this.controls.set('zoomControl', {
        id: 'zoomControl',
        control: zoomControl,
        config: zoomConfig
      });

      this.controlState.zoomControlEnabled = true;
      return zoomControl;

    } catch (error) {
      console.error('Failed to add zoom control:', error);
      return null;
    }
  }

  /**
   * 切换全屏模式
   */
  toggleFullscreen() {
    const map = this.mapEngine?.getInstance();
    if (!map) return;

    try {
      const container = map.container;
      
      if (!this.isFullscreen.value) {
        // 进入全屏
        if (container.requestFullscreen) {
          container.requestFullscreen();
        } else if (container.mozRequestFullScreen) {
          container.mozRequestFullScreen();
        } else if (container.webkitRequestFullscreen) {
          container.webkitRequestFullscreen();
        } else if (container.msRequestFullscreen) {
          container.msRequestFullscreen();
        }
      } else {
        // 退出全屏
        if (document.exitFullscreen) {
          document.exitFullscreen();
        } else if (document.mozCancelFullScreen) {
          document.mozCancelFullScreen();
        } else if (document.webkitExitFullscreen) {
          document.webkitExitFullscreen();
        } else if (document.msExitFullscreen) {
          document.msExitFullscreen();
        }
      }
    } catch (error) {
      console.error('Failed to toggle fullscreen:', error);
    }
  }

  /**
   * 绑定全屏事件
   * @private
   */
  _bindFullscreenEvents() {
    const handleFullscreenChange = () => {
      const isFullscreen = !!(
        document.fullscreenElement ||
        document.mozFullScreenElement ||
        document.webkitFullscreenElement ||
        document.msFullscreenElement
      );

      this.isFullscreen.value = isFullscreen;
      this._triggerCallback('onFullscreenChange', isFullscreen);

      // 更新全屏按钮样式
      this.toggleButtonActive('fullscreen', isFullscreen);
    };

    document.addEventListener('fullscreenchange', handleFullscreenChange);
    document.addEventListener('mozfullscreenchange', handleFullscreenChange);
    document.addEventListener('webkitfullscreenchange', handleFullscreenChange);
    document.addEventListener('msfullscreenchange', handleFullscreenChange);
  }

  /**
   * 处理复位按钮点击
   * @private
   */
  _handlePositionReset() {
    const map = this.mapEngine?.getInstance();
    if (!map) return;

    const resetView = this.options.jiaodu === 1 
      ? DEFAULT_MAP_VIEWS.angle1 
      : DEFAULT_MAP_VIEWS.angle2;

    map.centerAt(resetView, { duration: 1.0 });
  }

  /**
   * 移除控件
   * @param {string} id - 控件ID
   * @returns {boolean} 是否成功移除
   */
  removeControl(id) {
    const controlInfo = this.controls.get(id);
    if (!controlInfo) return false;

    const map = this.mapEngine?.getInstance();
    if (map && controlInfo.control) {
      map.removeControl(controlInfo.control);
    }

    this.controls.delete(id);
    
    // 如果是工具按钮，也从工具按钮Map中移除
    if (this.toolButtons.has(id)) {
      this.toolButtons.delete(id);
    }

    return true;
  }

  /**
   * 获取所有控件信息
   * @returns {Array} 控件信息数组
   */
  getAllControls() {
    return Array.from(this.controls.values());
  }

  /**
   * 获取控件状态
   * @returns {Object} 控件状态
   */
  getControlState() {
    return {
      ...this.controlState,
      isFullscreen: this.isFullscreen.value,
      buttonCount: this.toolButtons.size,
      controlCount: this.controls.size
    };
  }

  /**
   * 设置事件回调
   * @param {string} event - 事件名称
   * @param {Function} callback - 回调函数
   */
  on(event, callback) {
    const callbackName = `on${event.charAt(0).toUpperCase()}${event.slice(1)}`;
    if (this.callbacks.hasOwnProperty(callbackName)) {
      this.callbacks[callbackName] = callback;
    }
  }

  /**
   * 触发回调
   * @private
   * @param {string} callbackName - 回调名称
   * @param {any} data - 回调数据
   */
  _triggerCallback(callbackName, data) {
    const callback = this.callbacks[callbackName];
    if (typeof callback === 'function') {
      try {
        callback(data);
      } catch (error) {
        console.error(`Error in ${callbackName} callback:`, error);
      }
    }
  }

  /**
   * 清除所有控件
   */
  clearAllControls() {
    const map = this.mapEngine?.getInstance();
    if (!map) return;

    this.controls.forEach((controlInfo) => {
      try {
        map.removeControl(controlInfo.control);
      } catch (error) {
        console.warn('Failed to remove control:', error);
      }
    });

    this.controls.clear();
    this.toolButtons.clear();
  }

  /**
   * 获取地图控件信息
   * @returns {Object} 控件信息
   */
  getControlInfo() {
    const map = this.mapEngine?.getInstance();
    if (!map) return null;

    return {
      hasZoomControl: !!map.controls?.zoom,
      hasCompass: !!map.controls?.compass,
      hasScaleBar: !!map.controls?.scale,
      hasFullscreenButton: !!map.controls?.fullscreen,
      hasSceneModePicker: !!map.controls?.sceneModePicker,
      hasBaseLayerPicker: !!map.controls?.baseLayerPicker,
      hasNavigationHelp: !!map.controls?.navigationHelp
    };
  }

  /**
   * 销毁控件管理器
   */
  destroy() {
    this.clearAllControls();
    
    // 移除全屏事件监听器
    document.removeEventListener('fullscreenchange', this._handleFullscreenChange);
    document.removeEventListener('mozfullscreenchange', this._handleFullscreenChange);
    document.removeEventListener('webkitfullscreenchange', this._handleFullscreenChange);
    document.removeEventListener('msfullscreenchange', this._handleFullscreenChange);

    this.mapEngine = null;
    this.callbacks = {};
  }
}

/**
 * 地图控件组合函数
 * @param {Object} mapEngine - 地图引擎实例
 * @param {Object} options - 配置选项
 * @returns {Object} 控件管理器API
 */
export function useMapControls(mapEngine, options = {}) {
  const controls = ref(null);

  /**
   * 初始化控件管理器
   */
  const initControls = () => {
    controls.value = new MapControls(mapEngine, options);
    return controls.value;
  };

  /**
   * 获取控件管理器实例
   */
  const getControls = () => controls.value;

  /**
   * 销毁控件管理器
   */
  const destroy = () => {
    if (controls.value) {
      controls.value.destroy();
      controls.value = null;
    }
  };

  return {
    controls,
    initControls,
    getControls,
    destroy
  };
}
